package 算法.LeetCode91.每日打卡题目;

import 算法.NiuKe.ListNode;

/**
 * @author: 谢君臣
 * @create: 2021-03-02 10:45
 * @founction: XXXX
 *
    给定一个头结点为 head 的非空单链表，返回链表的中间结点。

    如果有两个中间结点，则返回第二个中间结点。
 */
public class day25 {
    public static void main(String[] args) {
        ListNode head = createnode(new int[]{1,2,3,4,5});
        middleNode(head);
    }

    private static ListNode createnode(int[] array) {
        ListNode head = new ListNode(array[0]);
        ListNode end = head;
        for (int i = 1; i < array.length; i++) {
            ListNode node = new ListNode(array[i]);
            end.next = node;
            end = end.next;
        }
        return head;
    }

    public static ListNode middleNode(ListNode head) {
        if (head.next==null)
            return head;
        else
        {
            ListNode l = head,q = head;
            while (q.next!=null&&q.next.next!=null){
                q = q.next.next;
                l = l.next;
            }
            if (q.next!=null){
                l = l.next;
            }
            return l;
        }
    }
}
